const mysql = require('mysql2/promise')

var pool = mysql.createPool({
  connectionLimit: 10,
  host: '127.0.0.1',
  user: 'root',
  port: 3306,
  password: 'hangcon456',
  waitForConnections: true,
  queueLimit: 0,
  database: 'test'
});

module.exports = pool;

exports.query = function (sql, params = []) {
  if (!params) {
    console.log('当前查询参数没有值，请查看db.js');
  }
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      if (err) throw err; // not connected!

      // Use the connection
      connection.query(sql, params, function (error, results, fields) {

        // 调试查询数据库的小方法
        console.log(`${sql}==>${params}=数据=>${results}`);

        // 释放连接池
        connection.release();

        // Handle error after the release.
        if (error) {
          console.log('db出现异常', error);
          return reject(error)
        }
        resolve(results)
      });
    });
  })
}